package com.zhentao.service.impl;

import com.alibaba.fastjson.JSON;
import com.zhentao.model.common.dtos.ResponseResult;
import com.zhentao.model.common.enums.AppHttpCodeEnum;
import com.zhentao.model.es.dto.UserSearchDto;
import com.zhentao.service.ApArticleSearchService;
import com.zhentao.service.ApUserSearchService;
import lombok.SneakyThrows;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.util.Sorter;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.jsoup.helper.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Date 2024/6/6 15:02
 * @Author xdm
 **/
@Service
public class ApArticleSearchServiceImpl implements ApArticleSearchService {

    @Autowired
    private RestHighLevelClient client;
    @Autowired
    private ApUserSearchService apUserSearchService;

    @SneakyThrows
    @Override
    public ResponseResult search(UserSearchDto dto) {
        //1.校验参数
        if (dto == null || StringUtils.isBlank(dto.getSearchWords())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }


        //添加搜索记录  userId先固定一个：  token-gateway-userId-interceptor-ThredLocal -get
        apUserSearchService.insert("4", dto.getSearchWords());



        //2.查询es
        SearchRequest searchRequest = new SearchRequest("app_info_article");
        SearchSourceBuilder builder = new SearchSourceBuilder();

        //查询条件
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

        QueryStringQueryBuilder queryBuilder = QueryBuilders.queryStringQuery(dto.getSearchWords())
                .field("title").field("content").defaultOperator(Operator.OR);

        boolQueryBuilder.must(queryBuilder);

        //查询小于minDate的数据
        if (dto.getMinBehotTime() != null) {

            RangeQueryBuilder rangeQueryBuilder =
                    QueryBuilders.rangeQuery("publishTime")
                            .lt(dto.getMinBehotTime().getTime());
            boolQueryBuilder.filter(rangeQueryBuilder);
        }

        //分页查询
        builder.from(0);
        builder.size(dto.getPageSize());

        //按照发布时间进行降序
        builder.sort("publishTime", SortOrder.DESC);

        //关键字的高亮显示

        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.preTags("<font style='color:red'>");
        highlightBuilder.postTags("</font>");
        builder.highlighter(highlightBuilder);


        //查询
        builder.query(boolQueryBuilder);
        searchRequest.source(builder);
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

        SearchHit[] searchHits = searchResponse.getHits().getHits();

        //封装结果
        List<Map> list = new ArrayList<>();

        for (SearchHit hit : searchHits) {
            String json = hit.getSourceAsString();
            System.out.println("json=======" + json);
            Map map = JSON.parseObject(json, Map.class);


            //设置高亮
            if (hit.getHighlightFields() != null) {
                Text[] texts = hit.getHighlightFields().get("title").getFragments();
                String title = StringUtils.join(texts);
                System.out.println(title);

                map.put("h_title", title);
            }


            list.add(map);
        }
        System.out.println("list===" + list);
        return ResponseResult.okResult(list);
    }
}
